﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WCS_Utility.Enums;
using WCS_Utility.ConstString;

namespace WCS_Utility.Extensions
{
    public static class StringExtensions
    {
        /// <summary>
        /// 通信类型转换成对应的枚举
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ComTypeEnum StringToEnum(this string value)
        {
            switch (value) 
            {
                case ConstStringData.Com_Tcp:
                    return ComTypeEnum.Tcp;
                case ConstStringData.Com_ModbusTcp:
                    return ComTypeEnum.ModbusTcp;
                default: return ComTypeEnum.Tcp;
            }
        }
        /// <summary>
        /// 数字字符串转换成指定枚举类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T StringToEnum<T>(this string value)
        {
            try
            {
                if (Enum.TryParse(typeof(T),value,out object result))
                {
                    return (T)result; 
                }
                return default(T);
            }
            catch(Exception ex)
            { 
                return default(T);
            }
        }

        /// <summary>
        /// 字符串转换成对应的index
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int? StringToIndex(this string value)
        {
            var flag = int.TryParse(value,out var result);
            if (flag)
            {
                return result;
            }
            return null;
        }
        /// <summary>
        /// 二进制转换成十六进制字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string BinaryToHex(this string value)
        { 
            var flag = Int32.TryParse(value, out var result);
            if (flag) 
            {
                return result.ToString("X2");
            }
            return null;
        }
    }
}
